const Koa = require("koa")
const Router = require("@koa/router")
const cors = require("@koa/cors")
const XLSX = require("xlsx")
const path = require("path")

const app = new Koa()
const router = new Router()

// Enable CORS
app.use(cors())

// Read Excel data
function readExcelData() {
    try {
        const filePath = path.join(__dirname, "data", "emotion_data.xlsx")
        const workbook = XLSX.readFile(filePath)
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)

        // Transform data to match expected format
        return jsonData.map((row) => ({
            date: row["评论时间"] || row["评论时间"],
            region: row["IP地区"] || row["IP地区"],
            rating: Number.parseInt(row["评分"]) || 0,
            comment: row["评价"] || "",
            words: row["评价分词"] || "",
            sentimentSnownlp: Number.parseFloat(row["情感得分_snownlp"]) || 0,
            sentimentDict: Number.parseFloat(row["情感得分_词典"]) || 0,
            sentimentScore: Number.parseFloat(row["情感得分"]) || 0,
            sentimentLabel: Number.parseInt(row["情感标签"]) || 0,
        }))
    } catch (error) {
        console.error("Error reading Excel file:", error)
        return []
    }
}

// API Routes
router.get("/api/data", async (ctx) => {
    const data = readExcelData()
    ctx.body = { success: true, data }
})

router.get("/api/stats", async (ctx) => {
    const data = readExcelData()

    // Calculate statistics with updated sentiment classification based on sentimentSnownlp
    const stats = {
        total: data.length,
        positiveCount: data.filter((item) => item.sentimentSnownlp >= 0.5 && item.sentimentSnownlp <= 1).length,
        negativeCount: data.filter((item) => item.sentimentSnownlp >= 0 && item.sentimentSnownlp < 0.2).length,
        neutralCount: data.filter((item) => item.sentimentSnownlp >= 0.2 && item.sentimentSnownlp < 0.5).length,
        avgRating: data.reduce((sum, item) => sum + item.rating, 0) / data.length,
        regionStats: {},
        ratingDistribution: {},
    }

    // Update region statistics to use sentimentSnownlp
    data.forEach((item) => {
        if (!stats.regionStats[item.region]) {
            stats.regionStats[item.region] = { count: 0, positive: 0, negative: 0 }
        }
        stats.regionStats[item.region].count++
        if (item.sentimentSnownlp >= 0.5 && item.sentimentSnownlp <= 1) stats.regionStats[item.region].positive++
        if (item.sentimentSnownlp >= 0 && item.sentimentSnownlp < 0.2) stats.regionStats[item.region].negative++
    })

    // Rating distribution
    data.forEach((item) => {
        if (!stats.ratingDistribution[item.rating]) {
            stats.ratingDistribution[item.rating] = 0
        }
        stats.ratingDistribution[item.rating]++
    })

    ctx.body = { success: true, stats }
})

router.get("/api/timeline", async (ctx) => {
    const data = readExcelData()

    // Update timeline calculation to use sentimentSnownlp
    const timeline = {}
    data.forEach((item) => {
        const date = item.date
        if (!timeline[date]) {
            timeline[date] = { positive: 0, negative: 0, neutral: 0, total: 0 }
        }
        timeline[date].total++
        if (item.sentimentSnownlp >= 0.5 && item.sentimentSnownlp <= 1) timeline[date].positive++
        else if (item.sentimentSnownlp >= 0 && item.sentimentSnownlp < 0.2) timeline[date].negative++
        else if (item.sentimentSnownlp >= 0.2 && item.sentimentSnownlp < 0.5) timeline[date].neutral++
    })

    const timelineArray = Object.keys(timeline)
        .map((date) => ({
            date,
            ...timeline[date],
        }))
        .sort((a, b) => new Date(a.date) - new Date(b.date))

    ctx.body = { success: true, timeline: timelineArray }
})

app.use(router.routes())
app.use(router.allowedMethods())

const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`)
})
